package dtu.k12tpm.pbs.activity;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import dtu.k12tpm.pbs.contact.Contact;
import dtu.k12tpm.pbs.regenerate_objects.SenderContactInfo;
import dtu.k12tpm.pbs.service.WebService;
import dtu.k12tpm.pbs.util.ContactProvider;
import dtu.k12tpm.pbs.util.MyXStream;

public class SenderContactListActivity extends MyActivity implements OnItemClickListener {
	private ArrayList<SenderContactInfo>	items	= new ArrayList<SenderContactInfo>();
	private ListView						lv;
	private ArrayAdapter<SenderContactInfo>	aa;
	ContactProvider							cp;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("New Groups Contact");
		setContentView(R.layout.sender_list);
		lv = (ListView) findViewById(R.id.List);
		try {
			cp = new ContactProvider();
			cp.setCr(getContentResolver());
			cp.setCur(getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "display_name ASC"));
			items = WebService.getSenderList(LoginActivity.getUsername());
			aa = new ArrayAdapter<SenderContactInfo>(this, R.layout.item_sender_info, items) {
				@Override
				public View getView(int position, View convertView, ViewGroup parent) {
					View v = convertView;
					if (v == null) {
						LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						v = vi.inflate(R.layout.item_sender_info, null);
					}

					SenderContactInfo contact = items.get(position);
					if (contact != null) {
						TextView tvFrom = (TextView) v.findViewById(R.id.tvFrom);
						TextView tvDate = (TextView) v.findViewById(R.id.tvDate);
						TextView tvTime = (TextView) v.findViewById(R.id.tvTime);
						TextView tvNote = (TextView) v.findViewById(R.id.tvNote);
						CheckBox CheckBox01 = (CheckBox) v.findViewById(R.id.CheckBox01);

						CheckBox01.setChecked(contact.isChecked());
						tvFrom.setText("From: " + contact.getSender());
						tvDate.setText("Date: " + contact.getDate());
						tvTime.setText("Time: " + contact.getTime());
						tvNote.setText("Notes: " + contact.getNote());
					}
					return v;
				}
			};
		} catch (Exception e) {
			new AlertDialog.Builder(this).setMessage("error: inbox contact " + e.getMessage()).show();
		}
		if (items.isEmpty()) {
			((TextView) findViewById(R.id.tvMessageEmptyList)).setText(R.string.msg_EmptyListContact);
		} else {
			((TextView) findViewById(R.id.tvMessageEmptyList)).setText("");
		}
		lv.setAdapter(aa);
		lv.setOnItemClickListener(this);
	}

	public void checkItemClick(View v) {
		int pos = lv.getPositionForView(v);
		items.get(pos).setChecked(((CheckBox) v).isChecked());
	}

	@Override
	protected void onRestart() {
		onCreate(getIntent().getExtras());
		super.onRestart();
	}

	public void AddContactClick(View v) {
		if (items.isEmpty()) {
			showToast("Don't have any contacts to add");
			return;
		}
		boolean hasCheck = false;
		for (SenderContactInfo sender : items) {
			if (sender.isChecked()) {
				hasCheck = true;
				break;
			}
		}
		if (hasCheck) {
			final ProgressDialog pd = showProgressDialog(null, "Please waiting...", false);
			new AddContactThread(pd).start();
		} else {
			showToast(R.string.msg_EmptyListContact);
		}
	}

	Handler	addContactHandler	= new Handler();

	public void setState(final ProgressDialog pd, final String msg) {
		addContactHandler.post(new Runnable() {

			@Override
			public void run() {
				pd.setMessage(msg);
			}
		});
	}

	public void notifyDataSetChanged(final ProgressDialog pd) {
		addContactHandler.post(new Runnable() {

			@Override
			public void run() {
				aa.notifyDataSetChanged();
				pd.dismiss();
			}
		});
	}

	class AddContactThread extends Thread {

		ProgressDialog	pd;

		public AddContactThread(ProgressDialog pd) {
			this.pd = pd;
		}

		public void run() {
			
			for (int j=0; j< items.size(); j++) {
				SenderContactInfo sender = items.get(j);
				if (sender.isChecked()) {
					try {
						ArrayList<Contact> myContacts = WebService.getPakageContact(sender.getId());
						Log.i("Size package contact", "" + myContacts.size());
						for (int i=0; i< myContacts.size(); i++) {
							final Contact contact = myContacts.get(i);
							if (cp.findContactWithName(contact.getDisplayName()) == 0) {
								cp.writeContact(contact);								
								myContacts.remove(i);
								setState(pd, "Saving '"+contact.getDisplayName()+"'.\nRemain: "+(myContacts.size()-i)+" contact(s)");
								i--;								
							} else {
								addContactHandler.post(new Runnable() {
									
									@Override
									public void run() {
										showToast("Contact '"+ contact.getDisplayName()+"' has been existed");
									}
								});
							}
						}
						if(myContacts.isEmpty()){
							WebService.deleteSender(sender.getId());
							items.remove(j);
							j--;
						}else{
							WebService.updateContentSender(MyXStream.toXML(myContacts), sender.getId());
						}
						notifyDataSetChanged(pd);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public void DeleteContactClick(View v) {
		if (items.isEmpty()) {
			showToast(R.string.msg_EmptyListContact);
			return;
		}
		boolean hasCheck = false;
		for (SenderContactInfo sender : items) {
			if (sender.isChecked()) {
				hasCheck = true;
				break;
			}
		}
		if (hasCheck) {
			showConfirmDialog("Delete Confirm", "Are you sure you want to delete?", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					try {
						int countDeleted = 0;
						int countCheck = 0;
						for (int i = 0; i < items.size(); i++) {
							SenderContactInfo info = items.get(i);
							if (info.isChecked()) {
								countCheck++;
								if (WebService.deleteSender(info.getId())) {
									countDeleted++;
									items.remove(i--);
								}
							}
						}
						if (countCheck > 0) {
							if (countDeleted > 0) {
								aa.notifyDataSetChanged();
							}
							if (items.isEmpty()) {
								((TextView) findViewById(R.id.tvMessageEmptyList)).setText(R.string.msg_EmptyListContact);
							}
							showToast("Deleted " + countDeleted + (countDeleted > 1 ? " item" : " items"));
						} else {
							showToast(R.string.msg_WhenDontSelectContact);
						}
					} catch (Exception e) {
						showMessageDialog("Exception", "inbox: " + e.getMessage());
					}
				}
			});
		} else {
			showToast(R.string.msg_WhenDontSelectContact);
		}
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
		Intent intent = new Intent(this, DetailSenderContactActivity.class);
		SenderContactInfo info = items.get(pos);
		intent.putExtra("id_package", info.getId());
		startActivity(intent);
	}

}
